<template>
  <div class="exams">
    <!-- 导航栏 -->
    <NavBar
      title="考试"
      :left-arrow="false"
      class="exams__navbar"
    >
      <template #right>
        <van-icon name="search" size="18" @click="onSearch" />
      </template>
    </NavBar>

    <!-- 搜索栏 -->
    <div v-if="showSearch" class="exams__search">
      <van-search
        v-model="searchKeyword"
        placeholder="搜索考试"
        @search="onSearchSubmit"
        @cancel="onSearchCancel"
        show-action
      />
    </div>

    <!-- 考试状态筛选 -->
    <div class="exams__filter">
      <van-tabs v-model:active="activeStatus" @change="onStatusChange" sticky>
        <van-tab title="全部" name="all" />
        <van-tab title="进行中" name="ongoing" />
        <van-tab title="即将开始" name="upcoming" />
        <van-tab title="已结束" name="finished" />
        <van-tab title="我的考试" name="mine" />
      </van-tabs>
    </div>

    <!-- 排序筛选 -->
    <div class="exams__toolbar">
      <van-dropdown-menu>
        <van-dropdown-item v-model="sortType" :options="sortOptions" />
        <van-dropdown-item v-model="filterSubject" :options="subjectOptions" title="科目" />
        <van-dropdown-item v-model="filterDifficulty" :options="difficultyOptions" title="难度" />
      </van-dropdown-menu>
    </div>

    <!-- 考试列表 -->
    <div class="exams__content">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div class="exams__list">
            <div
              v-for="exam in examList"
              :key="exam.id"
              class="exam-card"
              @click="onExamClick(exam)"
            >
              <!-- 考试状态标识 -->
              <div class="exam-card__status" :class="`exam-card__status--${exam.status}`">
                <span class="exam-card__status-text">{{ getStatusText(exam.status) }}</span>
              </div>

              <!-- 考试信息 -->
              <div class="exam-card__content">
                <div class="exam-card__header">
                  <h3 class="exam-card__title">{{ exam.title }}</h3>
                  <div class="exam-card__subject">{{ exam.subject }}</div>
                </div>
                
                <div class="exam-card__info">
                  <div class="exam-card__info-item">
                    <van-icon name="clock-o" size="14" />
                    <span>{{ exam.duration }}分钟</span>
                  </div>
                  <div class="exam-card__info-item">
                    <van-icon name="question-o" size="14" />
                    <span>{{ exam.questionCount }}题</span>
                  </div>
                  <div class="exam-card__info-item">
                    <van-icon name="star" size="14" />
                    <span>{{ exam.difficulty }}</span>
                  </div>
                </div>
                
                <!-- 考试时间 -->
                <div class="exam-card__time">
                  <div class="exam-card__time-item">
                    <span class="exam-card__time-label">开始时间：</span>
                    <span class="exam-card__time-value">{{ exam.startTime }}</span>
                  </div>
                  <div class="exam-card__time-item">
                    <span class="exam-card__time-label">结束时间：</span>
                    <span class="exam-card__time-value">{{ exam.endTime }}</span>
                  </div>
                </div>
                
                <!-- 考试统计 -->
                <div class="exam-card__stats">
                  <div class="exam-card__stat">
                    <span class="exam-card__stat-value">{{ exam.participantCount }}</span>
                    <span class="exam-card__stat-label">参与人数</span>
                  </div>
                  <div class="exam-card__stat">
                    <span class="exam-card__stat-value">{{ exam.passRate }}%</span>
                    <span class="exam-card__stat-label">通过率</span>
                  </div>
                  <div v-if="exam.myScore !== null" class="exam-card__stat">
                    <span class="exam-card__stat-value">{{ exam.myScore }}</span>
                    <span class="exam-card__stat-label">我的成绩</span>
                  </div>
                </div>
                
                <!-- 操作按钮 -->
                <div class="exam-card__actions">
                  <van-button
                    v-if="exam.status === 'ongoing' && !exam.hasParticipated"
                    type="primary"
                    size="small"
                    @click.stop="onStartExam(exam)"
                  >
                    开始考试
                  </van-button>
                  <van-button
                    v-else-if="exam.status === 'ongoing' && exam.hasParticipated && !exam.isCompleted"
                    type="warning"
                    size="small"
                    @click.stop="onContinueExam(exam)"
                  >
                    继续考试
                  </van-button>
                  <van-button
                    v-else-if="exam.status === 'finished' && exam.hasParticipated"
                    type="default"
                    size="small"
                    @click.stop="onViewResult(exam)"
                  >
                    查看成绩
                  </van-button>
                  <van-button
                    v-else-if="exam.status === 'upcoming'"
                    type="default"
                    size="small"
                    disabled
                  >
                    未开始
                  </van-button>
                </div>
              </div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>

    <!-- 底部标签栏 -->
    <TabBar />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'
import NavBar from '@/components/common/NavBar.vue'
import TabBar from '@/components/common/TabBar.vue'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 搜索相关
const showSearch = ref(false)
const searchKeyword = ref('')

// 状态筛选
const activeStatus = ref('all')

// 排序和筛选
const sortType = ref('default')
const filterSubject = ref('all')
const filterDifficulty = ref('all')

// 排序选项
const sortOptions = [
  { text: '默认排序', value: 'default' },
  { text: '开始时间', value: 'start_time' },
  { text: '结束时间', value: 'end_time' },
  { text: '参与人数', value: 'participant' },
  { text: '通过率', value: 'pass_rate' }
]

// 科目选项
const subjectOptions = [
  { text: '全部科目', value: 'all' },
  { text: '前端开发', value: 'frontend' },
  { text: '后端开发', value: 'backend' },
  { text: '数据库', value: 'database' },
  { text: '算法', value: 'algorithm' },
  { text: '系统设计', value: 'system' }
]

// 难度选项
const difficultyOptions = [
  { text: '全部难度', value: 'all' },
  { text: '简单', value: 'easy' },
  { text: '中等', value: 'medium' },
  { text: '困难', value: 'hard' }
]

// 列表相关
const examList = ref([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const page = ref(1)
const pageSize = 10

// 模拟考试数据
const mockExams = [
  {
    id: 1,
    title: 'JavaScript 基础知识测试',
    subject: '前端开发',
    difficulty: '简单',
    duration: 60,
    questionCount: 30,
    startTime: '2024-01-20 09:00',
    endTime: '2024-01-20 18:00',
    status: 'ongoing',
    participantCount: 156,
    passRate: 78,
    hasParticipated: false,
    isCompleted: false,
    myScore: null
  },
  {
    id: 2,
    title: 'Vue.js 框架进阶考试',
    subject: '前端开发',
    difficulty: '中等',
    duration: 90,
    questionCount: 45,
    startTime: '2024-01-19 10:00',
    endTime: '2024-01-19 17:00',
    status: 'finished',
    participantCount: 89,
    passRate: 65,
    hasParticipated: true,
    isCompleted: true,
    myScore: 85
  },
  {
    id: 3,
    title: 'Node.js 后端开发测试',
    subject: '后端开发',
    difficulty: '中等',
    duration: 75,
    questionCount: 40,
    startTime: '2024-01-21 14:00',
    endTime: '2024-01-21 20:00',
    status: 'upcoming',
    participantCount: 0,
    passRate: 0,
    hasParticipated: false,
    isCompleted: false,
    myScore: null
  },
  {
    id: 4,
    title: 'React Hooks 实战考试',
    subject: '前端开发',
    difficulty: '困难',
    duration: 120,
    questionCount: 50,
    startTime: '2024-01-20 08:00',
    endTime: '2024-01-20 22:00',
    status: 'ongoing',
    participantCount: 234,
    passRate: 45,
    hasParticipated: true,
    isCompleted: false,
    myScore: null
  },
  {
    id: 5,
    title: 'MySQL 数据库优化',
    subject: '数据库',
    difficulty: '困难',
    duration: 100,
    questionCount: 35,
    startTime: '2024-01-18 09:00',
    endTime: '2024-01-18 18:00',
    status: 'finished',
    participantCount: 67,
    passRate: 52,
    hasParticipated: true,
    isCompleted: true,
    myScore: 92
  }
]

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    ongoing: '进行中',
    upcoming: '即将开始',
    finished: '已结束'
  }
  return statusMap[status] || '未知'
}

// 搜索
const onSearch = () => {
  showSearch.value = !showSearch.value
  if (!showSearch.value) {
    searchKeyword.value = ''
    loadExams(true)
  }
}

const onSearchSubmit = () => {
  loadExams(true)
}

const onSearchCancel = () => {
  showSearch.value = false
  searchKeyword.value = ''
  loadExams(true)
}

// 状态切换
const onStatusChange = () => {
  loadExams(true)
}

// 加载考试列表
const loadExams = async (reset = false) => {
  if (reset) {
    page.value = 1
    examList.value = []
    finished.value = false
  }
  
  loading.value = true
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    let filteredExams = [...mockExams]
    
    // 状态筛选
    if (activeStatus.value !== 'all') {
      if (activeStatus.value === 'mine') {
        filteredExams = filteredExams.filter(exam => exam.hasParticipated)
      } else {
        filteredExams = filteredExams.filter(exam => exam.status === activeStatus.value)
      }
    }
    
    // 搜索筛选
    if (searchKeyword.value) {
      filteredExams = filteredExams.filter(exam =>
        exam.title.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
        exam.subject.toLowerCase().includes(searchKeyword.value.toLowerCase())
      )
    }
    
    // 科目筛选
    if (filterSubject.value !== 'all') {
      const subjectMap = {
        frontend: '前端开发',
        backend: '后端开发',
        database: '数据库',
        algorithm: '算法',
        system: '系统设计'
      }
      filteredExams = filteredExams.filter(exam =>
        exam.subject === subjectMap[filterSubject.value]
      )
    }
    
    // 难度筛选
    if (filterDifficulty.value !== 'all') {
      const difficultyMap = {
        easy: '简单',
        medium: '中等',
        hard: '困难'
      }
      filteredExams = filteredExams.filter(exam =>
        exam.difficulty === difficultyMap[filterDifficulty.value]
      )
    }
    
    // 排序
    if (sortType.value === 'start_time') {
      filteredExams.sort((a, b) => new Date(a.startTime) - new Date(b.startTime))
    } else if (sortType.value === 'end_time') {
      filteredExams.sort((a, b) => new Date(a.endTime) - new Date(b.endTime))
    } else if (sortType.value === 'participant') {
      filteredExams.sort((a, b) => b.participantCount - a.participantCount)
    } else if (sortType.value === 'pass_rate') {
      filteredExams.sort((a, b) => b.passRate - a.passRate)
    }
    
    // 分页
    const start = (page.value - 1) * pageSize
    const end = start + pageSize
    const newExams = filteredExams.slice(start, end)
    
    if (reset) {
      examList.value = newExams
    } else {
      examList.value.push(...newExams)
    }
    
    // 判断是否还有更多数据
    if (newExams.length < pageSize || end >= filteredExams.length) {
      finished.value = true
    }
    
    page.value++
  } catch (error) {
    showToast('加载失败')
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  loadExams(true)
}

// 上拉加载
const onLoad = () => {
  if (!finished.value) {
    loadExams()
  }
}

// 考试点击
const onExamClick = (exam) => {
  router.push(`/exam/${exam.id}`)
}

// 开始考试
const onStartExam = (exam) => {
  if (!userStore.isLoggedIn) {
    showDialog({
      title: '提示',
      message: '请先登录后再参加考试',
      confirmButtonText: '去登录'
    }).then(() => {
      router.push('/login')
    })
    return
  }
  
  showDialog({
    title: '开始考试',
    message: `确定要开始「${exam.title}」考试吗？\n考试时长：${exam.duration}分钟\n题目数量：${exam.questionCount}题`,
    confirmButtonText: '开始考试',
    cancelButtonText: '取消'
  }).then(() => {
    router.push(`/exam/${exam.id}/start`)
  })
}

// 继续考试
const onContinueExam = (exam) => {
  showDialog({
    title: '继续考试',
    message: `您有未完成的考试「${exam.title}」，是否继续？`,
    confirmButtonText: '继续考试',
    cancelButtonText: '取消'
  }).then(() => {
    router.push(`/exam/${exam.id}/continue`)
  })
}

// 查看成绩
const onViewResult = (exam) => {
  router.push(`/exam/${exam.id}/result`)
}

// 页面初始化
onMounted(() => {
  loadExams(true)
})
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';
@import '@/styles/mixins.scss';

.exams {
  min-height: 100vh;
  background: $gray-50;
  padding-bottom: $tabbar-height;

  &__navbar {
    background: white;
    border-bottom: 1px solid $border-color;
  }

  &__search {
    background: white;
    padding: $spacing-xs $spacing-base;
    border-bottom: 1px solid $border-color;
  }

  &__filter {
    background: white;
    
    :deep(.van-tabs__nav) {
      background: white;
    }
    
    :deep(.van-tab) {
      font-size: $font-size-sm;
    }
  }

  &__toolbar {
    background: white;
    border-bottom: 1px solid $border-color;
  }

  &__content {
    flex: 1;
  }

  &__list {
    padding: $spacing-base;
  }
}

.exam-card {
  background: white;
  border-radius: $border-radius-lg;
  margin-bottom: $spacing-base;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all $transition-duration-base;
  position: relative;
  
  &:active {
    transform: scale(0.98);
  }

  &__status {
    position: absolute;
    top: 0;
    right: 0;
    padding: $spacing-xs $spacing-base;
    border-bottom-left-radius: $border-radius-lg;
    
    &--ongoing {
      background: $success-color;
    }
    
    &--upcoming {
      background: $warning-color;
    }
    
    &--finished {
      background: $gray-400;
    }
  }

  &__status-text {
    color: white;
    font-size: $font-size-xs;
    font-weight: $font-weight-medium;
  }

  &__content {
    padding: $spacing-base;
    padding-top: $spacing-xl;
  }

  &__header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: $spacing-base;
  }

  &__title {
    font-size: $font-size-lg;
    font-weight: $font-weight-medium;
    color: $text-color;
    margin: 0;
    flex: 1;
    margin-right: $spacing-base;
  }

  &__subject {
    background: $primary-color;
    color: white;
    padding: $spacing-xs $spacing-sm;
    border-radius: $border-radius-base;
    font-size: $font-size-xs;
    white-space: nowrap;
  }

  &__info {
    display: flex;
    gap: $spacing-base;
    margin-bottom: $spacing-base;
  }

  &__info-item {
    display: flex;
    align-items: center;
    gap: $spacing-xs;
    font-size: $font-size-sm;
    color: $text-color-light;
    
    .van-icon {
      color: $text-color-lighter;
    }
  }

  &__time {
    margin-bottom: $spacing-base;
  }

  &__time-item {
    display: flex;
    font-size: $font-size-sm;
    margin-bottom: $spacing-xs;
    
    &:last-child {
      margin-bottom: 0;
    }
  }

  &__time-label {
    color: $text-color-light;
    width: 80px;
  }

  &__time-value {
    color: $text-color;
  }

  &__stats {
    display: flex;
    justify-content: space-around;
    padding: $spacing-base 0;
    border-top: 1px solid $border-color;
    border-bottom: 1px solid $border-color;
    margin-bottom: $spacing-base;
  }

  &__stat {
    text-align: center;
  }

  &__stat-value {
    display: block;
    font-size: $font-size-lg;
    font-weight: $font-weight-medium;
    color: $primary-color;
  }

  &__stat-label {
    font-size: $font-size-xs;
    color: $text-color-light;
  }

  &__actions {
    text-align: right;
  }
}

// 响应式适配
@include respond-below(480px) {
  .exam-card {
    &__content {
      padding: $spacing-sm;
      padding-top: $spacing-lg;
    }
    
    &__header {
      flex-direction: column;
      align-items: flex-start;
      gap: $spacing-xs;
    }
    
    &__title {
      margin-right: 0;
    }
    
    &__info {
      flex-wrap: wrap;
    }
    
    &__stats {
      flex-direction: column;
      gap: $spacing-xs;
      
      .exam-card__stat {
        display: flex;
        justify-content: space-between;
        text-align: left;
      }
    }
  }
}
</style>